<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <div>
      <Card title="表单数据映射">
        <div class="p-2">
          <Select
            :options="moduleList"
            v-model:value="formCode"
            class="w-200px"
            showSearch
            optionFilterProp="name"
            :field-names="{ label: 'name', value: 'code' }"
            :disabled="true"
            :get-popup-container="getPopupContainer"
          />
        </div>
        <Table :dataSource="params?.maps" :columns="columns" :pagination="false">
          <template #tztj="{ index, record }">
            <div class="flex">
              <Select
                :options="formGetFieldsMainData"
                v-model:value="record['sourceField']"
                class="w-1/2"
                style="margin-right: 5px"
                optionFilterProp="label"
                showSearch
                :disabled="index != 0"
                :get-popup-container="getPopupContainer"
              />

              <Select
                :options="dests"
                v-model:value="record['destField']"
                class="w-1/2"
                style="margin-right: 10px"
                optionFilterProp="label"
                showSearch
                :disabled="index != 0"
                :get-popup-container="getPopupContainer"
              />
            </div>
          </template>
          <template #action="{ index, record }">
            <div class="flex gap-2">
              <a-button
                type="primary"
                @click="handleAddMap(record, index)"
                size="small"
                v-if="index == 0"
              >
                新增
              </a-button>
              <a-button type="primary" @click="handleAddAllMap()" size="small" v-if="index == 0">
                全部新增
              </a-button>
              <a-button
                type="primary"
                size="small"
                @click="handleDelete(1, index)"
                v-if="index != 0"
              >
                删除
              </a-button>
            </div>
          </template>
        </Table>
      </Card>
      <Card
        title="嵌套表映射"
        style="margin-top: 10px"
        v-if="formGetNestFieldsList.length && formGetNestFields.length"
      >
        <Table :dataSource="params?.mapsNest" :columns="columns" :pagination="false">
          <template #tztj="{ index, record }">
            <div class="flex">
              <Select
                :options="formGetNestFieldsList"
                v-model:value="record['sourceField']"
                class="w-1/2"
                style="margin-right: 5px"
                optionFilterProp="label"
                showSearch
                :disabled="index != 0"
                :get-popup-container="getPopupContainer"
              />

              <Select
                :options="formGetNestFields"
                v-model:value="record['destField']"
                class="w-1/2"
                style="margin-right: 10px"
                optionFilterProp="label"
                showSearch
                :disabled="index != 0"
                :get-popup-container="getPopupContainer"
              />
            </div>
          </template>
          <template #action="{ index, record }">
            <div class="flex gap-2">
              <a-button
                type="primary"
                @click="handleAddMapNest(record, index)"
                size="small"
                v-if="index == 0"
              >
                新增
              </a-button>
              <a-button
                type="primary"
                size="small"
                @click="handleDelete(2, index)"
                v-if="index != 0"
              >
                删除
              </a-button>
            </div>
          </template>
        </Table>
      </Card>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { Table, Select, Card } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFormGetFields, getFormGetNestFields } from '/@/api/flowManage/flowManage';
  import { isArray, isEmpty } from '/@/utils/is';
  import { getModulesAll } from '/@/api/system/system';
  import {
    getFormGetFieldsByFlowTypeCode,
    getFormGetNestFieldsByTypeCode,
    getFormGetNestFormCode,
  } from '/@/api/formDesign/formDesign';
  import { isTypeMatched } from './operationColumnLink.data';
  import { BasicColumn } from '/@/components/Table';
  import { cloneDeep } from 'lodash-es';

  const columns: BasicColumn[] = [
    {
      title: '映射',
      dataIndex: 'tztj',
      key: 'tztj',
      align: 'center',
      slots: { customRender: 'tztj' },
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'action',
      key: 'action',
      slots: { customRender: 'action' },
      width: 100,
    },
  ];

  export default defineComponent({
    name: 'FieldMappingModal',
    components: {
      BasicModal,
      Table,
      Select,
      Card,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      const getTitle = '表单数据映射';
      const formGetFieldsData = ref<Recordable>([]);
      const dests = ref<Recordable[]>([]);
      const params = ref<Recordable>({});
      const formCode = ref('');
      const flowTypeCode = ref('');
      const sourceFormNest = ref('');

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '800px' });
        try {
          formCode.value = data?.formCode;
          flowTypeCode.value = data?.flowTypeCode;
          if (isEmpty(data.params)) {
            params.value = {
              destForm: '', //源表单
              destFormNest: '',
              maps: [
                {
                  appendable: 'false',
                  destField: '',
                  editable: 'false',
                  sourceField: '',
                },
              ],
              mapsNest: [
                {
                  appendable: 'false',
                  destField: '',
                  editable: 'false',
                  sourceField: '',
                },
              ],
              sourceForm: formCode.value, //当前表单
              sourceFormNest: '',
            };
          } else {
            params.value = cloneDeep(data?.params || { maps: [] });
            if (isArray(params.value.maps)) {
              params.value.maps.unshift({
                appendable: 'false',
                destField: '',
                editable: 'false',
                sourceField: '',
              });
            } else {
              params.value.maps = [
                {
                  appendable: 'false',
                  destField: '',
                  editable: 'false',
                  sourceField: '',
                },
              ];
            }
            if (isArray(params.value.mapsNest)) {
              params.value.mapsNest.unshift({
                appendable: 'false',
                destField: '',
                editable: 'false',
                sourceField: '',
              });
            } else {
              params.value.mapsNest = [
                {
                  appendable: 'false',
                  destField: '',
                  editable: 'false',
                  sourceField: '',
                },
              ];
            }
          }

          getFormGetFieldsMainData();
          getModulesAllData();
          getFormGetFieldsByFlowTypeCodeData();
          getFormGetNestFieldsByTypeCodeData();
          getFormGetNestFieldsData();
          getFormGetNestFormCodeData();
        } catch (err) {
          console.error(err);
        }
      });
      //取得主表中嵌套表的表单编码
      const getFormGetNestFormCodeData = async () => {
        const res = await getFormGetNestFormCode({ formCode: formCode.value });
        sourceFormNest.value = res?.nestFormCode;
      };
      const moduleList = ref<Recordable[]>([]);
      //获取所有模块
      const getModulesAllData = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };
      //获取所选表流程字段
      const getFormGetFieldsByFlowTypeCodeData = async () => {
        dests.value = [];
        const data = (await getFormGetFieldsByFlowTypeCode({ typeCode: flowTypeCode.value })) || {};
        params.value.destForm = data?.formCode;
        if (data && isArray(data.fields)) {
          data.fields.forEach((item) => {
            delete item.options;
            dests.value.push({
              ...item,
              value: item.name,
              label: item.title,
            });
          });
        }
      };
      //获取所选嵌套表的字段
      const formGetNestFields = ref<Recordable[]>([]);
      const getFormGetNestFieldsByTypeCodeData = async () => {
        formGetNestFields.value = [];
        const data = (await getFormGetNestFieldsByTypeCode({ typeCode: flowTypeCode.value })) || [];
        params.value.destFormNest = data?.nestFormCode;
        if (data && isArray(data.nestFormFields)) {
          data?.nestFormFields?.forEach((item) => {
            delete item.options;
            formGetNestFields.value.push({
              ...item,
              value: item.name,
              label: item.title,
            });
          });
        }
      };
      //主表获取嵌套表的字段
      const formGetNestFieldsList = ref<Recordable[]>([]);
      const getFormGetNestFieldsData = async () => {
        formGetNestFieldsList.value = [];
        const data = (await getFormGetNestFields({ formCode: formCode.value })) || [];
        data.forEach((item) => {
          delete item.options;
          formGetNestFieldsList.value.push({
            ...item,
            value: item.name,
            label: item.title,
          });
        });
      };

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          params.value.sourceForm = formCode.value; //当前表单
          params.value.sourceFormNest = sourceFormNest.value; //当前选择表单
          const formData = cloneDeep(params.value);
          formData.maps.splice(0, 1);
          formData.mapsNest.splice(0, 1);
          closeModal();
          emit('success', { params: formData });
        } catch (err) {
          console.error(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      const handleAddMap = (record, index) => {
        const sources = formGetFieldsMainData.value;
        const _dests = dests.value;
        if (!record['sourceField'] || !record['destField']) {
          createMessage.warning('请选择表单域');
          return;
        }
        if (!isTypeMatched(record['sourceField'], record['destField'], sources, _dests)) {
          return;
        }
        let isFound = false; //是否重复映射
        const trId = `${record['sourceField']}_${record['destField']}`;
        //排除当前第一个过滤
        params.value.maps
          .filter((_, i) => i != index)
          .forEach((item) => {
            const _trId = `${item['sourceField']}_${item['destField']}`;
            if (_trId == trId) {
              isFound = true;
            }
          });

        if (isFound) {
          createMessage.warning('存在重复映射！');
          return;
        }
        params.value.maps.unshift({
          appendable: 'false',
          destField: '',
          editable: 'false',
          sourceField: '',
        });
        params.value.maps = [...params.value.maps];
      };
      const handleDelete = (type, index) => {
        if (type == 1) {
          params.value.maps.splice(index, 1);
          params.value.maps = [...params.value.maps];
        } else if (type == 2) {
          params.value.mapsNest.splice(index, 1);
          params.value.mapsNest = [...params.value.mapsNest];
        }
      };

      const formGetFieldsMainData = ref<Recordable[]>([]);
      //获取主表字段
      const getFormGetFieldsMainData = () => {
        try {
          if (formCode.value) {
            getFormGetFields({ formCode: formCode.value }).then((res) => {
              formGetFieldsMainData.value = res || [];
              if (isArray(formGetFieldsMainData.value)) {
                formGetFieldsMainData.value.forEach((item) => {
                  item.value = item.name;
                  item.label = item.title;
                  delete item.options;
                });

                formGetFieldsMainData.value.push({
                  value: 'flowId',
                  label: '流程ID',
                });

                formGetFieldsMainData.value.push({
                  value: 'FormDAO_NEW_ID',
                  label: 'ID',
                });
              }
            });
          }
        } catch (err) {
          console.error('getFormGetFieldsMainData', err);
        }
      };
      // 添加字段名相同的映射
      function handleAddAllMap() {
        const sources = formGetFieldsMainData.value;
        const _dests = dests.value;
        for (let one in sources) {
          for (let key in _dests) {
            if (sources[one].value == _dests[key].value) {
              var trId = 'tr_' + sources[one].value + '_' + _dests[key].value;
              // 检测trId是否已存在
              var isFound = false;
              //排除当前第一个过滤
              params.value.maps
                .filter((_, i) => i != 0)
                .forEach((item) => {
                  const _trId = 'tr_' + `${item['sourceField']}_${item['destField']}`;
                  if (_trId == trId) {
                    isFound = true;
                  }
                });
              if (isFound) {
                createMessage.warning('存在重复映射！');
                return;
              }
              const obj = {
                appendable: 'false',
                destField: _dests[key].value,
                editable: 'false',
                sourceField: sources[one].value,
              };
              params.value.maps.splice(1, 0, obj);
            }
          }
        }
      }

      //新增嵌套表

      const handleAddMapNest = (record, index) => {
        if (!record.sourceField || !record.destField) {
          createMessage.warning('请选择表单域！');
          return;
        }
        const sourcesNest = formGetNestFieldsList.value;
        const destsNest = formGetNestFields.value;
        if (!isTypeMatched(record.sourceField, record.destField, sourcesNest, destsNest)) {
          return;
        }
        // 检测trId是否已存在
        var isFound = false;

        const trId = `${record['sourceField']}_${record['destField']}`;
        params.value.mapsNest
          .filter((_, i) => i != index)
          .forEach((item) => {
            const _trId = `${item['sourceField']}_${item['destField']}`;
            if (_trId == trId) {
              isFound = true;
            }
          });
        if (isFound) {
          createMessage.warning('存在重复映射！');
          return;
        }

        params.value.mapsNest.unshift({
          appendable: 'false',
          destField: '',
          editable: 'false',
          sourceField: '',
        });
        params.value.mapsNest = [...params.value.mapsNest];
      };

      const getPopupContainer = (triggerNode) => triggerNode?.parentNode;

      return {
        registerModal,
        getTitle,
        handleSubmit,
        columns,
        formGetFieldsData,
        handleAddMap,
        handleDelete,
        formGetFieldsMainData,
        handleAddAllMap,
        params,
        dests,
        moduleList,
        formCode,
        handleAddMapNest,
        formGetNestFieldsList,
        formGetNestFields,
        getPopupContainer,
      };
    },
  });
</script>
